/*
 * @Descripttion:
 * @version:
 * @Author: xcb
 * @Date: 2021-04-02 10:39:25
 * @LastEditors: yangyongtao
 * @LastEditTime: 2024-03-13 11:13:33
 */
import axios from "axios";
import router from "../router";
import Cookies from "js-cookie";
import { ElMessage } from "element-plus";

// 请求超时时间
// axios.defaults.timeout = 10000 * 5;

// 请求基础URL
if (import.meta.env.DEV) {
  axios.defaults.baseURL = "/";
} else {
  axios.defaults.baseURL = "http://10.6.88.2:8686/swns";
  //axios.defaults.baseURL = "http://10.6.13.222:8083";
  //axios.defaults.baseURL = "https://10.68.180.138:443/swns";
}

// post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

axios.interceptors.request.use((config) => {
  // 为请求头添加Authorization字段为服务端返回的token
  config.headers.Authorization = "cf4092ad-27ac-42da-9346-b3de7c730758";

  // if (import.meta.env.DEV) {
  //   config.headers.Authorization = "cf4092ad-27ac-42da-9346-b3de7c730758";
  // } else {
  //   config.headers.Authorization = JSON.parse(
  //     localStorage.getItem("userList")
  //   ).token;
  // }

  // return config是固定用法 必须有返回值
  return config;
});

// 请求携带cookie
axios.defaults.withCredentials = false;

// // 请求拦截器
axios.interceptors.request.use(
  (config) => {
    let loctoken = localStorage.getItem('sed-token')
    if(loctoken){
      config.headers["token"] = loctoken
    }else{
      if (Cookies.get("token", { domain: "" })) {
        config.headers["token"] = Cookies.get("token", { domain: "" });
      } else {
        config.headers["token"] = Cookies.get("token");
      }
    } 
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          ElMessage.error("请求失败，请重试");
          router.replace({ name: "Error_500" });
          break;
        case 401:
          ElMessage.error("请求失败，请重试");
          router.replace({ name: "Error_401" });
          break;
        case 404:
          ElMessage.error("请求失败，请重试");
          router.replace({ name: "Error_404" });
          break;
        case 444:
          ElMessage.error({
            message: "登录过期请重新登录!",
            duration: 1500,
            onClose: () => {
              // 跳转页面 不需要时注释下面这行
              //window.top.location = error.response.headers.location;
            },
          });
          break;
        default:
          return Promise.reject(error.response);
      }
    }
  }
);

/**
 * get方法，对应get请求
 */
export function get(url, params, info = "") {
  return new Promise((resolve, reject) => {
    axios
      .get(url + info, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

/**
 * post方法，对应post请求
 * info为 true，formData格式
 * info为 undefined或false，是json格式
 */
export function post(url, data = {}, info = false) {
  return new Promise((resolve, reject) => {
    let newData: any = data;
    if (info) {
      //  转formData格式
      newData = new FormData();
      for (let i in data) {
        newData.append(i, data[i]);
      }
    }

    axios
      .post(url, newData)
      .then((res: any) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

/**
 * 封装put请求
 */
export function put(url, params = {}, info = "") {
  return new Promise((resolve, reject) => {
    axios.put(url + info, params).then(
      (res) => {
        resolve(res.data);
      },
      (err) => {
        reject(err.data);
      }
    );
  });
}

/**
 * 封装delete请求
 */
export function axiosDelete(url, params = {}, info = "") {
  return new Promise((resolve, reject) => {
    axios
      .delete(url + info, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

/**
 * 封装下载请求
 */

export function fileDownload(url, params: any = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, {
        responseType: "blob", //服务器响应的数据类型，可以是'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'，默认是'json'
      })
      .then((res: any) => {
        const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); // 构造一个blob对象来处理数据，并设置文件类型
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = params.name + ".xlsx"; //下载后文件名
        link.click();

        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
